Namespace("org.wattdepot.gdata.makahiki");

// http://code.google.com/apis/visualization/documentation/gallery/genericimagechart.html

// Creates an Energy Data visualization for the last 24 hours.
org.wattdepot.gdata.makahiki.EnergyRank = function(configuration) {
  var configuration = configuration;
  
  // Returns the leader of the competition and their current energy use.
  function calculateLeader(rollingHoursDataTable) {
    // Sort the rows in the table based on last known energy.  
    // Note col 0 is identifier and col 1 is timestamp.
    rollingHoursDataTable.sort([{column: 2}]);
    // First 3 rows are null, so row index 3 is the top user.
    leader = rollingHoursDataTable.getValue(3, 0);
    currentEnergy = rollingHoursDataTable.getValue(3, 2);
    return {
      leader: leader,
      currentEnergy: currentEnergy
    }
  }
  
  // Calculates the rank and current energy of the source.
  function calculateRankInfo(rollingHoursDataTable, source) {
    // Store source identifier so that we can get it later.
    var sourceRow = configuration.getRollingEnergyRow(source);
    var sourceName = rollingHoursDataTable.getValue(sourceRow, 0);
    var currentEnergy = rollingHoursDataTable.getValue(sourceRow, 2);
    //console.log("Original row index is " + sourceRow);
    
    // Sort the rows in the table based on last known energy.  
    // Note col 0 is identifier and col 1 is timestamp.
    rollingHoursDataTable.sort([{column: 2}]);
    // Return the index of our source row plus 1.  First 3 rows are null values, so we actually subtract 2.
    var rank = rollingHoursDataTable.getFilteredRows([{column: 0, value: sourceName}])[0] - 2;
    return {
      currentEnergy: currentEnergy,
      rank: rank
    }
  }

  // Insert the rank and energy into the specified elements.
  function draw(rankId, energyId, sourceInfo) {
    // Get the rank element.
    var element = document.getElementById(rankId);
    element.innerHTML = "#" + sourceInfo.rank;
    
    // Get the energy element.
    element = document.getElementById(energyId);
    element.innerHTML = "" + sourceInfo.currentEnergy + " kWh";
  }
  
  // Insert the leader into the specified element.
  function insertLeader(elementId, leaderInfo) {
    var element = document.getElementById(elementId);
    element.innerHTML = leaderInfo.leader;
  }

  return {
    // Public interface to this function.
    draw : draw,
    insertLeader : insertLeader,
    calculateRankInfo : calculateRankInfo,
    calculateLeader: calculateLeader
  };
}
